package com.dchh.android.suverynew.act;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.dchh.android.suverynew.R;
import com.dchh.android.suverynew.base.SBaseActivity;
import com.dchh.android.suverynew.common.SPreferencesManager;
import com.dhcc.android.base.base.MSApplication;
import com.dhcc.android.base.common.bean.KeyValueBean;
import com.dhcc.android.base.common.view.MyActorPopWindow;
import com.dhcc.android.base.common.view.MyLoadingDialog;
import com.dhcc.android.base.db.DBManagerUtil;
import com.dhcc.android.base.utils.CommenUtil;
import com.dhcc.android.base.utils.Constants;
import com.dhcc.android.base.utils.FileUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 估产作物选择
 *
 * @author zhoudan
 * @date 2016年3月25日
 */
public class GCZwSelectActivity extends SBaseActivity {

    private ListView listview;
    private LinearLayout next;
    private List<Map<String, String>> zwlist = new ArrayList<Map<String, String>>();
    private SimpleAdapter adapter;
    private List<KeyValueBean> kvlist = new ArrayList<KeyValueBean>();
    private String root;
    private String taskName;
    private String dbPath;
    private DBManagerUtil dbManagerUtil;
    private List<String> fieldList1 = new ArrayList<String>();
    private List<String> fieldList2 = new ArrayList<String>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yield_guchan_zw_select);
    }

    @Override
    protected void setTitle(TextView toolbar_title) {
        toolbar_title.setText("估产作物选择");
    }

    @Override
    protected void initView() {
        root = SPreferencesManager.getValue(MSApplication.TASK_SAVE_PATH,
                FileUtil.getSavePath());

        taskName = Constants.currentTask.getTitle();
        dbPath = root + "/" + taskName + "/DEMAND/DEMAND.db";
        dbManagerUtil = DBManagerUtil.getInstance(dbPath, this);

        savaMark();

        kvlist = dbManagerUtil.getZWDatas("DIC_ZW", new KeyValueBean("PID", "VALUE", "CLASSIFICATION"), "CLASSIFICATION='农作物（100）'", dbPath);

        listview = (ListView) findViewById(R.id.zw_list);
        adapter = new SimpleAdapter(this, zwlist, R.layout.yield_guchan_zw_item, new String[]{"ZWMC"}, new int[]{R.id.zwmc});
        listview.setAdapter(adapter);


        next = (LinearLayout) findViewById(R.id.next_layout);
        next.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (zwlist.size() > 0) {
                    getResearchDatas();
                } else {
                    CommenUtil.toast("请先选择作物", GCZwSelectActivity.this);
                }
            }
        });
        setNavigationOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Constants.zwList.clear();
                GCZwSelectActivity.this.finish();
            }
        });
    }

    MyActorPopWindow.OnSelectListener selectListener = new MyActorPopWindow.OnSelectListener() {

        @Override
        public void onSelect(List<Map<String, String>> results) {
            zwlist = Constants.setListToList(results, zwlist);
            adapter.notifyDataSetChanged();
        }

        @Override
        public void OnSingleSelect(Map<String, String> map) {
        }
    };

    private void getResearchDatas() {
        String gc_dbpath = root + "/" + taskName + "/TASK/YIELD/DATA.db";
        String mj_dbpath = root + "/" + taskName + "/TASK/TRANSPORT/DATA.db";
        DBManagerUtil gc_dbutil = DBManagerUtil.getInstance(gc_dbpath, this);
        DBManagerUtil mj_dbutil = DBManagerUtil.getInstance(mj_dbpath, this);

        if (fieldList1.size() == 0) {
            fieldList1.add("ZWBH");
            fieldList1.add("ZW");
            fieldList1.add("ZWMJ");
            fieldList1.add("YFBHU");
            fieldList1.add("DKBHU");
            fieldList1.add("PID");
        }
        if (fieldList2.size() == 0) {
            fieldList2.add("SNZWBH");
            fieldList2.add("SNZWMC");
            fieldList2.add("SNZWMJ");
            fieldList2.add("YFBHU");
            fieldList2.add("DKBHU");
        }

        Constants.showDialog(this, "正在提取面积调查数据，请稍候...");
        for (Map<String, String> map : zwlist) {
            //判断对应的作物数据是否提取出来了
            int count = gc_dbutil.getCount(gc_dbpath, "估产表", " ZWBH='" + map.get("ZWBH") + "'");
            System.out.println("--" + map.get("ZWMC") + "--count--：" + count);
            if (count == 0) {
                List<Map<String, String>> zwdatas = mj_dbutil.getListData("作物" + Constants.currentTask.getRefrence(), fieldList1, "ZWBH='" + map.get("ZWBH") + "'", mj_dbpath);
                System.out.println("--" + map.get("ZWMC") + "--zw数据--：" + zwdatas.size());
                if (zwdatas != null && zwdatas.size() > 0) {
                    gc_dbutil.saveZWResearchDatasFORGC(Constants.currentCycle.getLabel(), Constants.currentTable.getLabel(), zwdatas, "估产表", gc_dbpath);
                }

                List<Map<String, String>> ssdatas = mj_dbutil.getListData("设施" + Constants.currentTask.getRefrence(), fieldList2, "SNZWBH='" + map.get("ZWBH") + "'", mj_dbpath);
                System.out.println("--" + map.get("ZWMC") + "--ss数据--：" + ssdatas.size());
                if (ssdatas != null && ssdatas.size() > 0) {
                    gc_dbutil.saveSSResearchDatasFORGC(Constants.currentCycle.getLabel(), Constants.currentTable.getLabel(), ssdatas, "估产表", gc_dbpath);
                }
            }
        }

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                Constants.zwList = zwlist;
                Constants.closeDialog();

                Dialog dialog = MyLoadingDialog.createLoadingDialog(GCZwSelectActivity.this, "正在载入，请稍候...");
                Constants.DIALOG = dialog;
                Constants.DIALOG.show();

                Intent intent = new Intent();
                intent.setClass(GCZwSelectActivity.this, GCMapSelectActivity.class);
                intent.putExtra("taskName", taskName);
                startActivity(intent);
                overridePendingTransition(R.anim.push_right_in, R.anim.push_left_out);
            }
        }, 1000);
    }


    /**
     * 保存选择，为恢复做准备
     */
    private void savaMark() {
        // 保存信息
        SPreferencesManager.saveValue(MSApplication.USERNAME, Constants.USERNAME);
        SPreferencesManager.saveValue(MSApplication.PASSWORD, Constants.PASSWORD);
        SPreferencesManager.saveValue(MSApplication.PERIOD_CODE,
                Constants.currentCycle.getCode());
        SPreferencesManager.saveValue(MSApplication.PERIOD_LABEL,
                Constants.currentCycle.getLabel());
        SPreferencesManager.saveValue(MSApplication.TABLE_CODE,
                Constants.currentTable.getCode());
        SPreferencesManager.saveValue(MSApplication.TABLE_LABEL,
                Constants.currentTable.getLabel());
        SPreferencesManager.saveValue(MSApplication.TASK, taskName);
        SPreferencesManager.saveValue(MSApplication.EXCEPTION_FLAG, false);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.gcz_select_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.add_operate) {
            MyActorPopWindow pw = new MyActorPopWindow(this, findViewById(R.id.contentArea), selectListener);
            pw.show(kvlist, zwlist, new KeyValueBean("ZWBH", "ZWMC"), false);
        }
        return true;
    }
}
